<template>
  <el-upload :data="avatarUploadParam"
    :action="signatureData.host"
    :accept="accept"
    :show-file-list="false"
    :on-success="successHandle"
    :on-error="handleError"
    :before-upload="beforeUpload"
    :on-progress="uploadProgress">
    <slot v-if="!uploading"></slot>
    <el-button v-if="uploading" type="primary" loading size="mini">上传中...</el-button>
    <el-progress :percentage="percent" v-show="percent < 100 && percent> 0 && showPercent" style="float:right;transform:translateY(80%)"></el-progress>
  </el-upload>
</template>

<script>
  import constant from '@U/constant'
  import userModel from '@M/user'
  export default {
    name:"Upload",
    props:{
      showPercent:{
        type:Boolean,
        default:false
      },
      uploadAppId:{
        type: String
      }, // appId
      imgSize: {
        type: Number
      }, // 图片大小
      accept: {
        type: String
      }, // 上传可选格式
      checkSuffix: {
        type: String,
        default: ''
      } // 检查后缀逗号隔开, 若字符串为空则不检查
    },
    data() {
      return {
        percent:0,
        signatureData:{host: '',dir:''},
        uploading: false,
        appId: '',
        uploadParam: {}, // 上传图片的共需参数
        avatarUploadParam: {}, // 上传封面图片的参数
      }
    },
    methods:{
      uploadProgress(event){
        this.percent = Math.floor(event.percent)
        this.$emit('sendPercent',this.percent)
      },
      handleError(){
        this.$message.warning("上传出错！")
      },
      successHandle(response, file, fileList){//上传成功
        this.$message.success('上传成功');
        let uploadImg = "" //图片回显
        if(this.$utils.isHttp(this.signatureData.host)){
          uploadImg = this.signatureData.host + "/" + this.avatarUploadParam.key
          this.$emit('uploadImage',uploadImg)
        }
      },
      beforeUpload(file){//上传之前
        //图片大小不超过 size
        if(file.size/1024/1024 > this.imgSize){
          this.$message.error('文件大小不能超过'+this.imgSize+'M!')
          return false
        }
        if(this.checkSuffix){
          let arr = this.checkSuffix.split(',')
          let checked = false
          arr.some(item => {
            let reg = new RegExp(item + '$', 'i')
            if(reg.test(file.name)){
              checked = true
              return true
            }
          })
          if(!checked){
            this.$message.error('请上传正确格式的文件')
            return false
          }
        }
        var temp = file.name.split(".")
        let uuid = this.UUID()
        var key = this.signatureData.dir + uuid + "." + temp[temp.length - 1]
        this.avatarUploadParam.policy = this.uploadParam.policy
        this.avatarUploadParam.OSSAccessKeyId = this.uploadParam.OSSAccessKeyId
        this.avatarUploadParam.success_action_status = this.uploadParam.success_action_status
        this.avatarUploadParam.signature = this.uploadParam.signature
        this.avatarUploadParam.key = key
        this.avatarUploadParam.name = file.name
        sessionStorage.setItem('fileName',file.name)
      },
      getOss(){//获取oss
        this.$postStream('/admin/instance/ccb/polyv/getOssInfo.do',{
          data:{
            appId:this.appId
          },
          success: res=> {
            if(res.success){
              if(!this.$utils.isHttp(this.signatureData.host)){
                this.signatureData.host = 'http://' + res.object.host
              }
              this.signatureData.dir = res.object.dir
              this.uploadParam={
                policy: res.object.policy,
                OSSAccessKeyId: res.object.accessid,
                success_action_status: "200",
                signature: res.object.signature
              }
            }
          }
        })
      },
      UUID(){//生成文件名
        var s = []
        var hexDigits = "0123456789abcdef"
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = "4"
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
        s[8] = s[13] = s[18] = s[23] = "-"
        var uuid = s.join("")
        return uuid
      }
    },
    mounted(){
      this.appId = this.uploadAppId || sessionStorage.getItem('appId') || ''
      this.channelId = sessionStorage.getItem('channelId')
      this.getOss()
    }
  }
</script>

<style lang="scss">
  .el-upload__input{
    display:none !important;
  }
</style>
